#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import logging
import os
from logging.handlers import RotatingFileHandler


def logger(name: str, log_file: str, level=logging.INFO, stream_level=logging.ERROR):
    """ return logger object """

    # Create the directory for the log file if it doesn't exist
    os.makedirs(os.path.dirname(log_file), exist_ok=True)

    # Create logger
    lg = logging.getLogger(name)
    lg.setLevel(logging.DEBUG)

    # Create file handler which logs messages
    fh = RotatingFileHandler(log_file, maxBytes=5 * 1024 * 1024, backupCount=7)  # 保留7天的日志文件，大小达到5M后进行分片
    # fh = logging.FileHandler(log_file)
    fh.setLevel(level)

    # Create console handler with a specific log level
    ch = logging.StreamHandler()
    ch.setLevel(stream_level)

    # Create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # Add the handlers to the logger
    lg.addHandler(fh)
    lg.addHandler(ch)

    return lg
